import webapp2
from Model import *
import datetime
from datetime import *
from google.appengine.ext import ndb
from google.appengine.api import memcache
import logging
from NotificationsUtils import *



class QuickRaceHandler(webapp2.RequestHandler):
    
    def post(self):
        logging.info("inside add to race")

        matchedRace = Race.query(ndb.AND(Race.Distance == float(self.request.POST.get('distance')),Race.Generation==RaceGenerate.Manual,Race.Status == RaceStatus.Before,
                                      Race.StartTime <= datetime.utcnow()+ timedelta(hours=3) + timedelta(minutes=5), Race.StartTime > datetime.utcnow()+ timedelta(hours=3) + timedelta(seconds=30))).order(Race.StartTime)
        if (matchedRace.count(10) == 0):
            logging.info("No user Race, searching for auto-generated races")
            #finds 'before' race, auto generated, and same distance - should be only 1 like that!
            matchedRace = Race.query(ndb.AND(Race.Distance == float(self.request.POST.get('distance')),Race.Generation==RaceGenerate.Auto,Race.Status == RaceStatus.Before)).order(Race.StartTime)
            if (matchedRace.count(100) == 0): #could not find race
                 self.response.out.write(json.dumps([{"raceID" : "-100"}]))
                 logging.info("No Auto-Generated races")
                 return None

        user = User.get_by_id(int(self.request.POST.get("userID")))
        race = matchedRace.get()
        logging.info("Found race")
        #add user to the race
        if(not user.key in race.Participants):
            race.Participants.append(user.key)

        #add to ready
        if(not user.key in race.ReadyParticipants):
            race.ReadyParticipants.append(user.key)

        race.put()
        logging.info(str(race.key.id()))
        #send to client relevant race data
        racesToJson = [{"raceID": race.key.id(), "Manager": race.Manager.get().Name,\
                        "Distance": race.Distance, "Time": str(race.StartTime),\
                        "Tags" : race.Tags, "Participants":race.NumOfParticipants,\
                        "ManagerId": race.Manager.id(), "Estimated":race.EstimatedTime}]
        # self.response.content_type = 'application/json'
        self.response.out.write(json.dumps(racesToJson))
        data = {'messageType':'RACER_READY'}
        res = sendMessageToClients(messageType = 'RACER_READY',registration_ids = [x.get().RegID for x in race.Participants] ,data=data )


